package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.JSONUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.domain.OrganizationRolesDO;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.service.OrganizationRolesService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
/**
 * 
 * <pre>
 * 机构信息表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/organizationNews")
public class OrganizationNewsController extends BaseController {
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private OrganizationRolesService organizationRolesService;
	@Autowired
	private UserService userService;

	private static final String BAIDU_MAP_API_KEY = "L4AySkO2z6zoWsN3yQbcbAblM1MePOi3";

	@GetMapping()
	@RequiresPermissions("jzweb:organizationNews:organizationNews")
	String OrganizationNews(){
	    return "jzweb/organizationNews/organizationNews";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:organizationNews:organizationNews")
	public Result<Page<OrganizationNewsDO>> list(OrganizationNewsDO organizationNewsDTO){
		String roleName = getRoleNames();
		Page<OrganizationNewsDO> page = null;
		if (!roleName.contains("超级用户角色")) {
			// 查询列表数据
			 page = organizationNewsService.selectPage(getPage(OrganizationNewsDO.class),
					organizationNewsService.convertToEntityWrapper("name", organizationNewsDTO.getName(),"type",organizationNewsDTO.getType(),"id" , this.getUser().getOrgId(),
							"org_code",organizationNewsDTO.getOrgCode()).orderBy("id", false));
		}else {
			// 查询列表数据
			page = organizationNewsService.selectPage(getPage(OrganizationNewsDO.class),
					organizationNewsService.convertToEntityWrapper("name", organizationNewsDTO.getName(),"type",organizationNewsDTO.getType(),
							"org_code",organizationNewsDTO.getOrgCode()).orderBy("id", false));
		}
		List list = new ArrayList();
		int n=0;
		for (int i = 0; i < page.getRecords().size(); i++) {
			OrganizationNewsDO obj = (OrganizationNewsDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.getByUserId(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.getByUserId(obj.getUpdaterId());
				if (userDO != null) {
					obj.setUpdaterName(userDO.getUsername());
				}
			}
			if (obj.getLeadingCadreId() != null){
				UserDO userDO = userService.getByUserId(obj.getLeadingCadreId());
				if (userDO != null) {
					obj.setLeadingCadreName(userDO.getUsername());
				}
			}

			list.add(obj);
		}
		List<OrganizationNewsDO> l = organizationNewsService.findByKv();
		for(OrganizationNewsDO o : l ){
			if(o.getEmployer()==null)continue;
			n+=o.getEmployer().split("}").length;
		}
		page.setRecords(list);
		System.out.println(n);
		return Result.ok(page);


	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:organizationNews:add")
	String add(Model model){
		model.addAttribute("");
	    return "jzweb/organizationNews/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:organizationNews:edit")
	String edit(@PathVariable("id") Long id,Model model){
		OrganizationNewsDO organizationNews = organizationNewsService.selectById(id);
		if (organizationNews.getLeadingCadreId() != null){
			UserDO userDO = userService.getByUserId(organizationNews.getLeadingCadreId());
			if (userDO != null) {
				organizationNews.setLeadingCadreName(userDO.getUsername());
			}
		}
//		if (experts.getUserId() != null){
//			UserDO userDO = userService.selectById(experts.getUserId());
//			if (userDO != null) {
//				experts.setName(userDO.getName());
//			}
//		}
		model.addAttribute("organizationNews", organizationNews);
	    return "jzweb/organizationNews/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:organizationNews:organizationNews")
	String info(@PathVariable("id") Long id,Model model){
		OrganizationNewsDO organizationNews = organizationNewsService.selectById(id);
		model.addAttribute("organizationNews", organizationNews);
		return "jzweb/organizationNews/info";
	}


	@Log("添加机构信息表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:organizationNews:add")
	public Result<String> save( OrganizationNewsDO organizationNews){
		OrganizationNewsDO organizationNewsDO = organizationNewsService.findOneByKv("name",organizationNews.getName());
		if(organizationNewsDO != null){
			return Result.fail("该机构已存在，请勿重复添加！");
		}else{
			organizationNewsService.insert(organizationNews);
			return Result.ok();
		}
	}
	
	@Log("修改机构信息表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:organizationNews:edit")
	public Result<String>  update( OrganizationNewsDO organizationNews){
		OrganizationNewsDO oldOrganizationNewsDO = organizationNewsService.selectById(organizationNews.getId());
		if(!oldOrganizationNewsDO.getName().equals(organizationNews.getName())){
			//模糊查询
//			OrganizationNewsDO organizationNewsDO = organizationNewsService.findOneByKv("name",organizationNews.getName());
			//修改为固定查询
			OrganizationNewsDO organizationNewsDO = organizationNewsService.selectOne(new EntityWrapper<OrganizationNewsDO>().eq("name",organizationNews.getName()));
			if(organizationNewsDO != null){
				return Result.fail("该机构代码已存在，请勿随意修改！");
			}
		}

		boolean update = organizationNewsService.updateById(organizationNews);
		return update ? Result.ok() : Result.fail();
	}

	@Log("根据企业或学校查省份")
	@ResponseBody
	@GetMapping("/selectProvince")
//	@RequiresPermissions("jzweb:organizationNews:edit")
	public Result<String>  selectProvince( @RequestParam(value = "name")String name) throws Exception {
		String province = getProvinceByAddress1(name);
		System.out.println("省份: " + province);
		return Result.ok(province);

	}

	@Log("给未赋值的单位或学校赋值省份")
	@ResponseBody
	@GetMapping("/getProvince")
//	@RequiresPermissions("jzweb:organizationNews:edit")
	public Result<String>  getProvince( ) throws Exception {
		List<OrganizationNewsDO> organizationNewsDOS = organizationNewsService.selectList(new EntityWrapper<>());
		List<OrganizationNewsDO> organizationsWithoutProvince  = organizationNewsDOS.stream()
				.filter(e -> StringUtils.isEmpty(e.getProvince()))
				.collect(Collectors.toList());

       // 创建一个列表用于收集失败的信息
		List<String> errorMessages = new ArrayList<>();

		List<OrganizationNewsDO> updatedOrganizations = organizationsWithoutProvince.stream()
				.map(e -> {
					try {
						e.setProvince(getProvinceByAddress1(e.getName()));
						return e; // 成功时返回实体对象
					} catch (Exception ex) {
						errorMessages.add("Failed to get province for " + e.getName() + ": " + ex.getMessage());
						return null; // 失败时返回null
					}
				})
				.filter(Objects::nonNull) // 移除null值
				.collect(Collectors.toList());

        // 执行批量更新
		boolean result = organizationNewsService.updateBatchById(updatedOrganizations);

		if (result && errorMessages.isEmpty()) {
			return Result.ok();
		} else {
			StringBuilder errorMessage = new StringBuilder("更新省份部分失败:\n");
			errorMessages.forEach(errorMessage::append);
			return Result.fail(errorMessage.toString());
		}
	}
	@Log("删除机构信息表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:organizationNews:remove")
	public Result<String>  remove( Long id){
		boolean b = organizationNewsService.deleteById(id);
        if(b){
        	List<OrganizationRolesDO> organizationRolesDOS = organizationRolesService.findByKv("org_id",id);
        	if(organizationRolesDOS != null && organizationRolesDOS.size() > 0){
        		return Result.fail("机构还存在机构角色信息，请先删除后继续！");
			}else{
				return Result.ok();
			}
		}
		return Result.fail();
	}
	
	@Log("批量删除机构信息表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:organizationNews:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		boolean b = organizationNewsService.deleteBatchIds(Arrays.asList(ids));
		if(b){
			int j = 0;
			for(int i=0;i<ids.length;i++){
				List<OrganizationRolesDO> organizationRolesDOS = organizationRolesService.findByKv("org_id",ids[i]);
				if(organizationRolesDOS != null && organizationRolesDOS.size() > 0){
					j++;
				}
			}
			if(j==0){
				return Result.ok();
			}else{
				return Result.fail("机构还存在机构角色信息，请先删除后继续！");
			}
		}else{
			return Result.fail();
		}

	}


//	private static final String API_URL = "https://api.tianyancha.com/api/v3/search/1";
//	private static final OkHttpClient client = new OkHttpClient();
//	private static final Gson gson = new Gson();
//	private static final String API_KEY = "YOUR_API_KEY_HERE"; // 替换为你的API密钥
//
//	/**  L4AySkO2z6zoWsN3yQbcbAblM1MePOi3
//	 * 根据企业名称查询所在省份。
//	 * @param companyName 企业名称
//	 * @return 省份名称，如果找不到，则返回null
//	 */
//	public static String getProvinceByCompanyName(String companyName) {
//		try {
//			String url = API_URL + "?key=" + API_KEY + "&name=" + companyName;
//			Request request = new Request.Builder()
//					.url(url)
//					.build();
//			Response response = client.newCall(request).execute();
//			if (!response.isSuccessful()) {
//				throw new IOException("Unexpected code " + response);
//			}
//			String responseBody = response.body().string();
//			JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
//			JsonObject data = jsonObject.getAsJsonObject("data");
//			JsonObject companyInfo = data.getAsJsonArray("list").get(0).getAsJsonObject();
//			String address = companyInfo.getAsJsonObject("regLocation").get("province").getAsString();
//			return address;
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}
//	}

//	public static void main(String[] args) {
//		String province = getProvinceByCompanyName("阿里巴巴集团");
//		System.out.println("阿里巴巴集团位于: " + province);
//	}


	public static void main(String[] args) {
		try {
//			String schoolOrCompanyName = "清华大学";
			String schoolOrCompanyName = "湖南金职伟业母婴护理有限公司";
			String province = getProvinceByAddress1(schoolOrCompanyName);
			System.out.println("省份: " + province);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	public static String getProvinceByAddress(String address) throws Exception {
//		String urlString = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + BAIDU_MAP_API_KEY;
//		URL url = new URL(urlString);
//		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		conn.setRequestMethod("GET");
//		conn.connect();
//
//		// 获取响应码
//		int responseCode = conn.getResponseCode();
//
//		if (responseCode != 200) {
//			throw new RuntimeException("HTTP GET Request Failed with Error code : " + responseCode);
//		}
//
//		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//		String inputLine;
//		StringBuilder response = new StringBuilder();
//		while ((inputLine = in.readLine()) != null) {
//			response.append(inputLine);
//		}
//		in.close();
//
//		// 解析JSON响应
//		JSONObject jsonResponse = new JSONObject(response.toString());
//		if ("0".equals(jsonResponse.getString("status"))) {
//			JSONObject result = jsonResponse.getJSONObject("result");
//			JSONObject addressComponent = result.getJSONObject("addressComponent");
//			return addressComponent.getString("province");
//		} else {
//			throw new RuntimeException("API Response Error: " + jsonResponse.getString("msg"));
//		}
//	}

	public static String getProvinceByAddress1(String address) throws Exception {
		String urlString = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + BAIDU_MAP_API_KEY;
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.connect();

		// 获取响应码
		int responseCode = conn.getResponseCode();

		if (responseCode != 200) {

			return "HTTP GET Request Failed with Error code : "+responseCode;
//			throw new RuntimeException("HTTP GET Request Failed with Error code : " + responseCode);
		}

		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// 解析JSON响应
		JSONObject jsonResponse = new JSONObject(response.toString());
		if ("0".equals(jsonResponse.getString("status"))) {
			JSONObject result = jsonResponse.getJSONObject("result");
			JSONObject location = result.getJSONObject("location");
			double lat = location.getDouble("lat");
			double lng = location.getDouble("lng");
			return getProvinceByCoordinates(lat, lng);
		} else {
			return "API Response Error : "+jsonResponse.getString("msg");
//			throw new RuntimeException("API Response Error: " + jsonResponse.getString("msg"));
		}
	}

	public static String getProvinceByCoordinates(double latitude, double longitude) throws Exception {
		String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?location=" + latitude + "," + longitude + "&output=json&ak=" + BAIDU_MAP_API_KEY;
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.connect();

		// 获取响应码
		int responseCode = conn.getResponseCode();

		if (responseCode != 200) {
			return "HTTP GET Request Failed with Error code : "+responseCode;
//			throw new RuntimeException("HTTP GET Request Failed with Error code : " + responseCode);
		}

		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// 解析JSON响应
		JSONObject jsonResponse = new JSONObject(response.toString());
		if ("0".equals(jsonResponse.getString("status"))) {
			JSONObject result = jsonResponse.getJSONObject("result");
			JSONObject addressComponent = result.getJSONObject("addressComponent");
			return addressComponent.getString("province");
		} else {
			return "API Response Error : "+jsonResponse.getString("msg");
//			throw new RuntimeException("API Response Error: " + jsonResponse.getString("msg"));
		}
	}
	
}
